import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:raze/lore/chronicle/user_chronicle.dart';

/// 可点击头像组件
/// 如果点击的是当前用户头像，则不添加点击事件
/// 如果不是当前用户，点击后跳转到他人主页
class ClickableAvatarWidget extends StatelessWidget {
  final String userId;
  final String avatarPath;
  final double width;
  final double height;
  final BoxDecoration? decoration;

  const ClickableAvatarWidget({
    super.key,
    required this.userId,
    required this.avatarPath,
    required this.width,
    required this.height,
    this.decoration,
  });

  @override
  Widget build(BuildContext context) {
    // 如果 userId 为空，直接返回头像，不添加点击事件
    if (userId.isEmpty) {
      return _buildAvatarWidget();
    }

    // 直接获取当前用户状态（不使用 Obx，避免嵌套问题）
    // 当用户状态改变时，组件会自然重新构建
    final userChronicle = Get.find<UserChronicle>();
    final currentUser = userChronicle.currentUser;
    final isCurrentUser = currentUser != null && currentUser.id == userId;

    final avatarWidget = _buildAvatarWidget();

    if (isCurrentUser) {
      // 如果是当前用户，不添加点击事件
      return avatarWidget;
    }

    // 如果不是当前用户，添加点击事件跳转到他人主页
    return GestureDetector(
      onTap: () {
        if (userId.isNotEmpty) {
          Get.toNamed('/other-home', parameters: {'userId': userId});
        }
      },
      child: avatarWidget,
    );
  }

  /// 构建头像组件
  Widget _buildAvatarWidget() {
    return decoration != null
        ? Container(
          width: width,
          height: height,
          decoration: decoration,
          child: ClipOval(
            child: Image.asset(
              avatarPath,
              width: width,
              height: height,
              fit: BoxFit.cover,
            ),
          ),
        )
        : ClipOval(
          child: Image.asset(
            avatarPath,
            width: width,
            height: height,
            fit: BoxFit.cover,
          ),
        );
  }
}
